<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="咨询方式" prop="type" style="width: 200px;">
        <el-select v-model="queryParams.type" placeholder="咨询方式" clearable>
          <el-option
              v-for="dict in consultation_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >去预约
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            :icon="showHistory ? 'Clock' : 'List'"
            @click="toggleHistory"
        >{{ showHistory ? '返回当前预约' : '查看历史记录' }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appointmentList" v-if="appointmentList.length>0">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="预约ID" align="center" prop="appointmentId"/>
      <el-table-column label="预约开始时间" align="center" prop="scheduledTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约结束时间" align="center" prop="scheduledTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="咨询方式" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="consultation_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="appointment_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="用户备注" align="center" prop="notes"/>
      <el-table-column label="记录状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.delFlag === '2' ? 'info' : 'success'">
            {{ scope.row.delFlag === '2' ? '历史记录' : '有效记录' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <template v-if="scope.row.delFlag === '0'">
            <el-button link type="primary" @click="handleView(scope.row)">查看详情</el-button>
            <el-button link type="primary" @click="handleConfirm(scope.row)" v-if="scope.row.status === '5'">
              确认结束咨询
            </el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" v-if="scope.row.status === '0'">取消预约
            </el-button>
            <el-button link type="primary" @click="handleReAppointment(scope.row)" v-if="scope.row.status === '4'">
              重新预约
            </el-button>
            <el-button link type="primary" @click="handleReAppointment(scope.row)" v-if="scope.row.status === '2'">
              再次预约
            </el-button>
            <el-button link type="primary" @click="handleReview(scope.row)" v-if="scope.row.status === '2'">
              填写评价
            </el-button>
          </template>

          <template v-else>
            <el-button link type="info" @click="handleView(scope.row)">查看详情</el-button>
            <el-tooltip content="该记录已归档" placement="top">
              <el-button link type="info" disabled>已失效</el-button>
            </el-tooltip>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-empty v-else description="暂无数据！请先去预约吧！"></el-empty>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改咨询预约对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="appointmentRef" :model="form" label-width="100px" disabled>
        <el-row :gutter="20">
          <!-- 左侧咨询师信息 -->
          <el-col :span="10">
            <el-card class="consultant-card">
              <div class="consultant-info">
                <div class="avatar-section">
                  <image-preview
                      :src="form.avatar"
                      class="profile-avatar"
                      :preview-src-list="[form.avatar]"
                  />
                  <h3>{{ form.counselorName }}</h3>
                  <div class="meta-info">
                    <dict-tag
                        :options="counselor_titles"
                        :value="form.title"
                        :type="form.title"
                    />
                  </div>
                </div>

                <el-divider/>

                <div class="contact-info">
                  <div class="info-item">
                    <el-icon>
                      <User/>
                    </el-icon>
                    <span>性别：</span>
                    <el-tag type="primary">{{ sexMapper(form.sex) }}</el-tag>
                  </div>
                  <div class="info-item">
                    <el-icon>
                      <Phone/>
                    </el-icon>
                    <span>电话：{{ form.phonenumber || '暂无' }}</span>
                  </div>
                  <div class="info-item">
                    <el-icon>
                      <Message/>
                    </el-icon>
                    <span>邮箱：{{ form.email || '暂无' }}</span>
                  </div>
                  <div class="info-item">
                    <el-icon>
                      <Location/>
                    </el-icon>
                    <span>地址：{{ form.address || '暂无' }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧预约信息 -->
          <el-col :span="14">
            <el-card class="appointment-card">
              <div class="form-section">
                <el-form-item label="预约开始时间" prop="startTime">
                  <el-input :value="parseTime(form.startTime, '{y}-{m}-{d} {h}:{i}')"/>
                </el-form-item>
                <el-form-item label="预约结束时间" prop="endTime"> <!-- 修正prop属性 -->
                  <el-input :value="parseTime(form.endTime, '{y}-{m}-{d} {h}:{i}')"/>
                </el-form-item>
                <el-form-item label="咨询方式" prop="type">
                  <el-radio-group v-model="form.type">
                    <el-radio-button
                        v-for="dict in consultation_type"
                        :key="dict.value"
                        :label="dict.value"
                    >{{ dict.label }}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="预约地址" v-if="form.type === '1'">
                  <el-input
                      v-model="form.address"
                      type="textarea"
                      :rows="4"
                      resize="none"
                  />
                </el-form-item>

                <el-form-item label="用户备注" prop="notes">
                  <el-input
                      v-model="form.notes"
                      type="textarea"
                      :rows="4"
                      placeholder="无备注信息"
                      resize="none"
                  />
                </el-form-item>

                <el-divider>状态信息</el-divider>

                <div class="status-info">
                  <div class="status-item">
                    <label>当前状态：</label>
                    <dict-tag
                        :options="appointment_status"
                        :value="form.appointmentStatus"
                        :type="form.appointmentStatus === '2' ? 'danger' : 'primary'"
                    />
                  </div>
                  <div class="status-item" v-if="form.reason">
                    <label>拒绝原因：</label>
                    <span class="reason-text">{{ form.reason }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>


    <!--  填写评价-->
    <el-dialog
        title="填写评价"
        v-model="reviewFlag"
        width="600"
        append-to-body
    >
      <el-form
          ref="reviewFormRef"
          :model="reviewForm"
          :rules="reviewRules"
          label-width="80px"
      >
        <el-form-item label="观察记录">
          <el-input type="textarea" v-model="reviewForm.observation" disabled autosize/>
        </el-form-item>
        <el-form-item label="评估结果">
          <el-input type="textarea" v-model="reviewForm.assessmentResult" disabled autosize/>
        </el-form-item>
        <el-form-item label="进展">
          <el-slider v-model="reviewForm.progressEvaluation" disabled/>
        </el-form-item>
        <el-form-item label="请评分" prop="userSatisfaction">
          <el-rate
              v-model="reviewForm.userSatisfaction"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              show-text
              :texts="['很差', '一般', '满意', '推荐', '力荐']"
          />
        </el-form-item>

        <el-form-item label="评价内容" prop="userComment">
          <el-input
              v-model="reviewForm.userComment"
              type="textarea"
              :rows="4"
              placeholder="请详细描述您的咨询体验"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reviewFlag = false">取 消</el-button>
          <el-button type="primary" @click="submitReview">提 交</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Appointment">
import {
  listAppointment,
  getAppointment,
  delAppointment, reAppointment,
} from "@/api/appointment/appointment";
import {parseTime} from "@/utils/ruoyi.js";
import {UploadFilled} from "@element-plus/icons-vue";
import ImageUpload from "@/components/ImageUpload/index.vue";
import {getCounselorResult, getResult, updateResult} from "@/api/result/result.js";
import {handleAppointmentEnd} from "@/api/websocket/websocket.js";

const {proxy} = getCurrentInstance();
const {
  consultation_type,
  appointment_status,
  sys_user_sex,
  counselor_titles
} = proxy.useDict('counselor_titles', 'sys_user_sex', 'consultation_type', 'appointment_status');

const appointmentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const daterangeScheduledTime = ref([]);
const reviewFlag = ref(false)
const showHistory = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    scheduledTime: null,
    type: null,
    status: null,
    notes: null,
    delFlag: '0'
  },
});

const {queryParams, form} = toRefs(data);

const reviewForm = reactive({
  userSatisfaction: 5,
  userComment: '',
  resultId: 0,
})

const reviewRules = reactive({
  userSatisfaction: [
    {required: true, message: '请选择评分', trigger: 'change'}
  ],
  userComment: [
    {required: true, message: '请输入评价内容', trigger: 'blur'},
    {min: 5, message: '评价内容至少5个字', trigger: 'blur'}
  ]
})

const handleConfirm = (row) => {
  console.log('row', row)
  proxy.$modal.confirm(`确认结束预约吗？`, '温馨提示', {
    confirmButtonText: '结束咨询',
    type: 'warning'
  }).then(() => {
    handleAppointmentEnd(row.counselorId, row.userId).then(res => {
      proxy.$modal.msgSuccess("咨询结束成功");
    })
  })
}

// 切换历史记录方法
const toggleHistory = () => {
  showHistory.value = !showHistory.value
  queryParams.value.delFlag = showHistory.value ? '2' : '0'
  getList()
}

const submitReview = () => {
  proxy.$refs['reviewFormRef'].validate(valid => {
    if (valid) {
      updateResult(reviewForm).then(res => {
        proxy.$modal.msgSuccess("评价成功");
        reviewFlag.value = false
      })
    }
  })
}

/**
 * 填写评价
 * @param row
 */
const handleReview = (row) => {
  getCounselorResult(row.appointmentId).then(res => {
    reviewForm.observation = res.data.observation
    reviewForm.assessmentResult = res.data.assessmentResult
    reviewForm.progressEvaluation = Number(res.data.progressEvaluation)
    reviewForm.resultId = Number(res.data.resultId)
  })
  reviewFlag.value = true
}

// 重新预约，跳转到咨询师详情页
function handleReAppointment(row) {
  let text = row.status == '4' ? '是否确认重新预约？' : row.status == '2' ? '是否再次预约？' : ''
  proxy.$modal.confirm(text).then(function () {
    // 逻辑删除掉上一条预约记录
    let data = {appointmentId: row.appointmentId}
    reAppointment(data).then(res => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess(res.msg);
        setTimeout(() => {
          return proxy.$router.push({
            path: '/counselorDetails',
            query: {
              counselorId: row.counselorId
            }
          })
        }, 500);
      }
    })

  }).catch(() => {
  });
}

//  性别字典映射
function sexMapper(value) {
  for (let i = 0; i < sys_user_sex.value.length; i++) {
    if (sys_user_sex.value[i].value === value) {
      return sys_user_sex.value[i].label;
    }
  }
}

/** 查询咨询预约列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  listAppointment(queryParams.value).then(response => {
    console.log("查询结果：", response)
    appointmentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 表单重置
function reset() {
  form.value = {
    appointmentId: null,
    userId: null,
    counselorId: null,
    scheduledTime: null,
    type: null,
    status: null,
    reason: null,
    notes: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  proxy.resetForm("appointmentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeScheduledTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$router.push({path: "/appointment"})
}

/** 查看按钮操作 */
function handleView(row) {
  reset();
  const _appointmentId = row.appointmentId || ids.value
  getAppointment(_appointmentId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "查看咨询预约";
  });
}

/** 取消按钮操作 */
function handleDelete(row) {
  const _appointmentIds = row.appointmentId || ids.value;
  proxy.$modal.confirm('是否确认取消咨询预约编号为"' + _appointmentIds + '"的数据项？').then(function () {
    return delAppointment(_appointmentIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("取消成功");
  }).catch(() => {
  });
}

onMounted(() => {
  getList();
})
</script>

<!-- 在style部分添加以下样式 -->
<style scoped lang="scss">
.consultant-card {
  height: 100%;

  /* 左侧内容居中 */
  .consultant-info {
    text-align: center;

    .avatar-section {
      display: flex;
      flex-direction: column;
      align-items: center;

      .profile-avatar {
        margin: 0 auto 15px;
      }

      h3 {
        margin-bottom: 8px;
      }

      .meta-info {
        margin-bottom: 15px;
      }
    }

    .contact-info {
      .info-item {
        display: flex;
        align-items: center;
        justify-content: center; /* 新增此行实现水平居中 */
        gap: 8px;
        margin: 12px 0;
      }
    }
  }
}

/* 右侧状态信息居中 */
.status-info {
  .status-item {
    display: flex;
    align-items: center;
    justify-content: center; /* 水平居中 */
    flex-direction: column; /* 垂直居中布局 */
    text-align: center;
    margin: 16px 0;

    /* 标签样式调整 */
    ::v-deep .el-tag {
      margin-top: 8px;
      width: fit-content; /* 自适应宽度 */
    }

    .reason-text {
      margin-top: 8px;
    }
  }
}
</style>

